import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/// @author: pengboboer
/// @createDate: 1/4/21
typedef OnLongPressCallback = Future<dynamic> Function(LongPressStartDetails details);

class ClickBackgroundWidget extends StatefulWidget {
  final Color backgroundColor;
  final Color selectColor;
  final Widget child;
  final Function onTap;
  final HitTestBehavior behavior;
  final OnLongPressCallback onLongPress;
  final bool isEnableLongPress;

  const ClickBackgroundWidget({Key key,
    this.backgroundColor = const Color(0xFF21263C),
    this.selectColor = const Color(0xFF191E31), this.child, this.onTap,
    this.behavior = HitTestBehavior.translucent,
    this.onLongPress, this.isEnableLongPress = true}) : super(key: key);
  @override
  _ClickBackgroundWidgetState createState() => _ClickBackgroundWidgetState();
}

class _ClickBackgroundWidgetState extends State<ClickBackgroundWidget> {
  Color color;
  bool isLongPress = false;
  LongPressStartDetails longDetails;

  @override
  void initState() {
    super.initState();
    color = widget.backgroundColor;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: widget?.behavior,
      onTap: widget?.onTap,
      onLongPress: () {
        if (!widget.isEnableLongPress) {
          return;
        }
        if (widget.onLongPress != null) {
          widget.onLongPress(longDetails).then((value) => reset());
          isLongPress = false;
        }
      },
      onLongPressStart: (de) {
        print("longstart");
        if (!widget.isEnableLongPress) {
          return;
        }
        longDetails = de;
        isLongPress = true;
        setState(() {
          color = widget.selectColor;
        });

      },
      onLongPressEnd: (de) {
        if (!widget.isEnableLongPress) {
          return;
        }
        isLongPress = false;
        print("longend");
        print(de);
        reset();
      },
      onTapDown: (detail){
        print("tapdown");
        setState(() {
          color = widget.selectColor;
        });
      },
      onTapUp: (detail) {
        Future.delayed(Duration(milliseconds: 50), (){
          reset();
        });
      },
      onTapCancel: () {
        if (isLongPress) {
          return;
        }
        reset();
      },
      child: Container(
        color: color,
        child: widget.child ?? Container(),
      ),
    );
  }

  void reset() {
    setState(() {
      color = widget.backgroundColor;
    });
  }
}
